<template>
  <div class="douluo-data-demo">
    <div class="header">
      <h1>🐉 斗罗大陆数据集成演示</h1>
      <p>使用TXT转Mock数据工具管理斗罗大陆章节内容</p>
    </div>

    <div class="demo-container">
      <!-- 当前状态卡片 -->
      <div class="status-card">
        <h3>📊 当前数据状态</h3>
        <div class="status-grid">
          <div class="status-item">
            <div class="status-number">{{ currentStats.totalChapters }}</div>
            <div class="status-label">总章节数</div>
          </div>
          <div class="status-item">
            <div class="status-number">{{ currentStats.freeChapters }}</div>
            <div class="status-label">免费章节</div>
          </div>
          <div class="status-item">
            <div class="status-number">{{ currentStats.vipChapters }}</div>
            <div class="status-label">VIP章节</div>
          </div>
          <div class="status-item">
            <div class="status-number">{{ formatNumber(currentStats.totalWords) }}</div>
            <div class="status-label">总字数</div>
          </div>
        </div>
      </div>

      <!-- 功能操作卡片 -->
      <div class="operations-card">
        <h3>🛠 数据操作</h3>
        
        <!-- 文件上传 -->
        <div class="operation-section">
          <h4>📁 TXT文件上传</h4>
          <div class="upload-area">
            <input 
              ref="fileInput"
              type="file" 
              accept=".txt"
              @change="handleFileSelect"
              style="display: none"
            >
                         <div 
               class="upload-zone"
               @click="handleUploadClick"
               @dragover.prevent
               @drop.prevent="handleFileDrop"
             >
              <div class="upload-icon">📄</div>
              <div class="upload-text">
                <p>点击选择或拖拽TXT文件到此处</p>
                <p class="upload-hint">支持斗罗大陆完整TXT文件</p>
              </div>
            </div>
            <button 
              v-if="selectedFile"
              @click="processFile"
              :disabled="processing"
              class="process-btn"
            >
              {{ processing ? '处理中...' : `处理文件: ${selectedFile.name}` }}
            </button>
          </div>
        </div>

        <!-- 示例数据 -->
        <div class="operation-section">
          <h4>🎯 示例数据</h4>
          <div class="sample-actions">
            <button @click="applySampleData" class="sample-btn">
              应用示例数据 (30章精彩内容)
            </button>
            <button @click="previewSampleData" class="preview-btn">
              预览示例数据
            </button>
            <button @click="exportData" class="export-btn">
              导出当前数据
            </button>
          </div>
        </div>

        <!-- 数据管理 -->
        <div class="operation-section">
          <h4>⚙️ 数据管理</h4>
          <div class="management-actions">
            <button @click="refreshData" class="refresh-btn">
              刷新统计
            </button>
            <button @click="resetData" class="reset-btn">
              重置为原始数据
            </button>
            <button @click="viewChapters" class="view-btn">
              查看章节列表
            </button>
          </div>
        </div>
      </div>

      <!-- 预览卡片 -->
      <div v-if="previewData.length > 0" class="preview-card">
        <h3>👀 数据预览</h3>
        <div class="preview-list">
          <div 
            v-for="chapter in previewData.slice(0, 5)" 
            :key="chapter.id"
            class="preview-item"
          >
            <div class="preview-header">
              <span class="chapter-title">{{ chapter.title }}</span>
              <span class="chapter-meta">
                {{ chapter.wordCount }}字 | 
                {{ chapter.isFree ? '免费' : `${chapter.price}书币` }}
              </span>
            </div>
            <div class="preview-content">
              {{ chapter.content.substring(0, 100) }}...
            </div>
          </div>
        </div>
        <div v-if="previewData.length > 5" class="preview-more">
          还有 {{ previewData.length - 5 }} 章内容...
        </div>
      </div>

      <!-- 结果消息 -->
      <div v-if="message" class="message-card" :class="messageType">
        <div class="message-content">{{ message }}</div>
        <button @click="clearMessage" class="message-close">×</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  getCurrentDouluoChapters,
  generateDouluoSampleData,
  applyDouluoSampleData,
  processDouluoLargeTxt,
  updateDouluoChapters,
  exportDouluoData
} from '@/utils/douluoDataIntegration'
import type { Chapter } from '@/types'

// 响应式数据
const selectedFile = ref<File | null>(null)
const processing = ref(false)
const previewData = ref<Chapter[]>([])
const message = ref('')
const messageType = ref<'success' | 'error' | 'info'>('info')

// 当前统计数据
const currentStats = reactive({
  totalChapters: 0,
  freeChapters: 0,
  vipChapters: 0,
  totalWords: 0
})

// 格式化数字
const formatNumber = (num: number): string => {
  return num.toLocaleString()
}

// 更新统计数据
const updateStats = () => {
  const chapters = getCurrentDouluoChapters()
  currentStats.totalChapters = chapters.length
  currentStats.freeChapters = chapters.filter(c => c.isFree).length
  currentStats.vipChapters = chapters.filter(c => c.isVip).length
  currentStats.totalWords = chapters.reduce((total, c) => total + c.wordCount, 0)
}

// 显示消息
const showMessage = (msg: string, type: 'success' | 'error' | 'info' = 'info') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 5000)
}

// 清除消息
const clearMessage = () => {
  message.value = ''
}

// 点击上传区域
const handleUploadClick = () => {
  const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
  fileInput?.click()
}

// 文件选择处理
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    selectedFile.value = target.files[0]
  }
}

// 文件拖拽处理
const handleFileDrop = (event: DragEvent) => {
  if (event.dataTransfer?.files && event.dataTransfer.files[0]) {
    selectedFile.value = event.dataTransfer.files[0]
  }
}

// 处理文件
const processFile = async () => {
  if (!selectedFile.value) {
    showMessage('请先选择文件', 'error')
    return
  }

  processing.value = true
  try {
    showMessage('正在处理文件，请稍候...', 'info')
    const chapters = await processDouluoLargeTxt(selectedFile.value)
    updateDouluoChapters(chapters)
    updateStats()
    previewData.value = chapters
    showMessage(`✅ 成功处理文件！生成了 ${chapters.length} 章内容`, 'success')
  } catch (error) {
    showMessage(`❌ 处理失败：${(error as Error).message}`, 'error')
  } finally {
    processing.value = false
  }
}

// 应用示例数据
const applySampleData = () => {
  try {
    applyDouluoSampleData()
    updateStats()
    showMessage('✅ 示例数据已成功应用！现在可以在网站中查看30章精彩内容', 'success')
  } catch (error) {
    showMessage(`❌ 应用失败：${(error as Error).message}`, 'error')
  }
}

// 预览示例数据
const previewSampleData = () => {
  try {
    const chapters = generateDouluoSampleData()
    previewData.value = chapters
    showMessage('📖 示例数据预览已加载', 'info')
  } catch (error) {
    showMessage(`❌ 预览失败：${(error as Error).message}`, 'error')
  }
}

// 导出数据
const exportData = () => {
  try {
    exportDouluoData()
    showMessage('✅ 数据已导出到下载文件夹', 'success')
  } catch (error) {
    showMessage(`❌ 导出失败：${(error as Error).message}`, 'error')
  }
}

// 刷新数据
const refreshData = () => {
  updateStats()
  showMessage('📊 统计数据已刷新', 'info')
}

// 重置数据
const resetData = () => {
  if (confirm('确定要重置为原始数据吗？这将清除所有导入的章节数据。')) {
    location.reload()
  }
}

// 查看章节
const viewChapters = () => {
  window.open('/novel/7', '_blank')
  showMessage('📖 已在新标签页中打开斗罗大陆', 'info')
}

// 组件挂载时初始化
onMounted(() => {
  updateStats()
})
</script>

<style scoped>
.douluo-data-demo {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.header p {
  color: #7f8c8d;
  font-size: 16px;
}

.demo-container {
  display: grid;
  gap: 20px;
}

.status-card,
.operations-card,
.preview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.status-card h3,
.operations-card h3,
.preview-card h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
}

.status-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-number {
  font-size: 24px;
  font-weight: bold;
  color: #3498db;
  margin-bottom: 4px;
}

.status-label {
  color: #7f8c8d;
  font-size: 14px;
}

.operation-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.operation-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.operation-section h4 {
  color: #34495e;
  margin-bottom: 12px;
}

.upload-area {
  margin-bottom: 16px;
}

.upload-zone {
  border: 2px dashed #bdc3c7;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.upload-zone:hover {
  border-color: #3498db;
  background: #f8f9fa;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.upload-text p {
  margin: 4px 0;
  color: #7f8c8d;
}

.upload-hint {
  font-size: 12px !important;
  color: #95a5a6 !important;
}

.process-btn {
  width: 100%;
  padding: 12px 24px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.process-btn:hover:not(:disabled) {
  background: #2980b9;
}

.process-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.sample-actions,
.management-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.sample-btn,
.preview-btn,
.export-btn,
.refresh-btn,
.reset-btn,
.view-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.sample-btn {
  background: #27ae60;
  color: white;
}

.sample-btn:hover {
  background: #229954;
}

.preview-btn {
  background: #f39c12;
  color: white;
}

.preview-btn:hover {
  background: #e67e22;
}

.export-btn {
  background: #8e44ad;
  color: white;
}

.export-btn:hover {
  background: #7d3c98;
}

.refresh-btn {
  background: #17a2b8;
  color: white;
}

.refresh-btn:hover {
  background: #138496;
}

.reset-btn {
  background: #dc3545;
  color: white;
}

.reset-btn:hover {
  background: #c82333;
}

.view-btn {
  background: #6c757d;
  color: white;
}

.view-btn:hover {
  background: #5a6268;
}

.preview-list {
  space-y: 12px;
}

.preview-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #3498db;
  margin-bottom: 12px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.chapter-title {
  font-weight: bold;
  color: #2c3e50;
}

.chapter-meta {
  font-size: 12px;
  color: #7f8c8d;
}

.preview-content {
  color: #34495e;
  line-height: 1.6;
  font-size: 14px;
}

.preview-more {
  text-align: center;
  color: #7f8c8d;
  font-style: italic;
  margin-top: 16px;
}

.message-card {
  position: relative;
  padding: 16px 40px 16px 16px;
  border-radius: 8px;
  margin-top: 20px;
}

.message-card.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message-card.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.message-card.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.message-content {
  font-size: 14px;
}

.message-close {
  position: absolute;
  top: 8px;
  right: 12px;
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: inherit;
  opacity: 0.7;
}

.message-close:hover {
  opacity: 1;
}

@media (max-width: 768px) {
  .status-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .sample-actions,
  .management-actions {
    flex-direction: column;
  }
  
  .sample-btn,
  .preview-btn,
  .export-btn,
  .refresh-btn,
  .reset-btn,
  .view-btn {
    width: 100%;
  }
}
</style> 